package org.apache.cordova.urovo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.device.ScanManager;
import java.util.ArrayList;
import org.apache.cordova.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class UrovoScanner extends CordovaPlugin {
	private final static String SCAN_ACTION = "urovo.rcv.message";
	private CallbackContext mMainCallback;
	private ScanManager mScanManager;

	private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			byte[] barcode = intent.getByteArrayExtra(ScanManager.DECODE_DATA_TAG);
            int barcodelen = intent.getIntExtra(ScanManager.BARCODE_LENGTH_TAG, 0);
            byte temp = intent.getByteExtra(ScanManager.BARCODE_TYPE_TAG, (byte) 0);
			String barcodeStr = new String(barcode, 0, barcodelen);

			JSONObject jsonResponse = new JSONObject();
			try {
				jsonResponse.put("event", "decode");
				jsonResponse.put("data", barcodeStr);
			} catch (JSONException e) {}
			PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, jsonResponse);
			pluginResult.setKeepCallback(true);
			mMainCallback.sendPluginResult(pluginResult);

			// mScanManager.stopDecode();
		}
	};

	@Override
	public void initialize(CordovaInterface cordova, CordovaWebView webView) {
		super.initialize(cordova, webView);

		mScanManager = new ScanManager();
	}

	@Override
	public void onPause(boolean multitasking) {
		super.onPause(multitasking);
		if(mScanManager != null) {
			mScanManager.stopDecode();
		}
		this.cordova.getActivity().unregisterReceiver(mScanReceiver);
	}
	@Override
	public void onResume(boolean multitasking) {
		super.onResume(multitasking);

        if (!mScanManager.getScannerState()) {
        	mScanManager.openScanner();
        }
        if (mScanManager.getOutputMode() != 0) {
			mScanManager.switchOutputMode(0);
		}

		IntentFilter filter = new IntentFilter();
		filter.addAction(SCAN_ACTION);
		this.cordova.getActivity().registerReceiver(mScanReceiver, filter);
	}

	@Override
	public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {

		if ("init".equals(action)) {
			mMainCallback = callbackContext;
			this.onResume(false);
			return true;
		} else if ("start".equals(action)) {
			mScanManager.stopDecode();
			try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            mScanManager.startDecode();
			return true;
		} else if ("stop".equals(action)) {
			mScanManager.stopDecode();
			return true;
		} 
		callbackContext.error(action + " is not a supported action");
		return false;
	}
}